<template>
  <div class="record-container">
    <el-tabs v-model="activeTab" @tab-click="handleTabChange" class="certificate-tabs">
      <el-tab-pane label="待办证" name="0"></el-tab-pane>
      <el-tab-pane label="办证中" name="1"></el-tab-pane>
      <el-tab-pane label="办结记录" name="2"></el-tab-pane>
    </el-tabs>
    <el-card class="filter-card">
      <el-form
        :inline="true"
        :model="queryParams"
        label-width="100px"
        class="filter-form"
      >
        <el-form-item label="载体">
          <el-select
            v-model="queryParams.zt"
            placeholder="请选择载体"
            clearable
            style="width: 200px"
          >
            <el-option label="联健元和" value="联健元和" />
            <el-option label="达博" value="达博" />
            <el-option label="科澜项目" value="科澜项目" />
            <el-option label="国科项目" value="国科项目" />
            <el-option label="黄埭项目" value="黄埭项目" />
            <el-option label="金扶梯" value="金扶梯" />
            <el-option label="北联新翼" value="北联新翼" />
            <el-option label="深圳项目" value="深圳项目" />
            <el-option label="西山项目" value="西山项目" />
            <el-option label="秦淮项目" value="秦淮项目" />
            <el-option label="双创中心" value="双创中心" />
            <el-option label="创界项目" value="创界项目" />
            <el-option label="江环项目" value="江环项目" />
            <el-option label="江北项目" value="江北项目" />
            <el-option label="拓展项目" value="拓展项目" />
            <el-option label="试点项目" value="试点项目" />
          </el-select>
        </el-form-item>
        <el-form-item label="企业名称" prop="companyName">
          <el-input
            v-model="queryParams.companyName"
            placeholder="请输入企业名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="入驻类型">
          <el-select
            v-model="queryParams.entryMode"
            placeholder="请选择入驻类型"
            clearable
            style="width: 200px"
          >
            <el-option label="实体企业" value="实体" />
            <el-option label="挂靠企业" value="挂靠" />
          </el-select>
        </el-form-item>
        <el-form-item label="证件类型" prop="certificationType">
          <el-input
            v-model="queryParams.certificationType"
            placeholder="请输入证件类型"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="list-card">
      <el-table
        v-loading="loading"
        :data="certificateList"
        class="certificate-table"
        style="width: 100%; border-radius: 14px; overflow: hidden"
        border
      >
        <el-table-column
          type="index"
          label="序号"
          width="80"
          align="left"
        /><el-table-column prop="zt" label="载体" align="left">
          <template #default="scope">
            <el-tag
              type="success"
              effect="plain"
              style="font-size: 13px; padding: 0 12px"
              >{{ scope.row.zt || "联健元和" }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="companyName"
          label="企业名称"
          width="400"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column prop="entryMode" label="入驻方式" align="left">
          <template #default="scope">
            <el-tag v-if="scope.row.entryMode" effect="plain">{{
              scope.row.entryMode
            }}</el-tag>
            <span v-else style="color: #bbb">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="companyClass" label="注册类型" align="left">
          <template #default="scope">
            <el-tag v-if="scope.row.companyClass" effect="plain">{{
              scope.row.companyClass
            }}</el-tag>
            <span v-else style="color: #bbb">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="certificationStatus" label="办证状态" align="left">
          <template #default="scope">
            <el-tag v-if="scope.row.certificationStatus == 0" type="info" effect="plain"
              >待办证</el-tag
            >
            <el-tag
              v-else-if="scope.row.certificationStatus == 1"
              type="warning"
              effect="plain"
              >办证中</el-tag
            >
            <el-tag
              v-else-if="scope.row.certificationStatus == 2"
              type="success"
              effect="plain"
              >已办结</el-tag
            >
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="activeTab !== '0'"
          prop="certificationType"
          label="办证类型"
          width="130"
          align="left"
        >
          <template #default="scope">
            <el-tag v-if="scope.row.certificationType" effect="plain">{{
              scope.row.certificationType
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          v-if="activeTab !== '0'"
          prop="certificationPersonnel"
          label="办证人"
          width="130"
          align="left"
        >
          <template #default="scope">
            <el-tag v-if="scope.row.certificationPersonnel" effect="plain">{{
              scope.row.certificationPersonnel
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="url" label="附件" v-if="activeTab === '2'" align="left">
          <template #default="scope">
            <el-link
              v-if="scope.row.url"
              :href="scope.row.url"
              target="_blank"
              type="primary"
              >查看</el-link
            >
            <span v-else style="color: #bbb">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="230" fixed="right" align="left">
          <template #default="{ row }">
            <el-button type="primary" link @click="viewCompanyProfile(row.companyId)">
              查看企业档案
            </el-button>
            <el-button
              type="primary"
              link
              v-if="row.certificationStatus == 0"
              @click="openStartDialog(row)"
              >开始办证</el-button
            >
            <el-button
              type="primary"
              link
              v-if="row.certificationStatus == 1"
              @click="openCertificationDialog(row)"
              >上传办证材料</el-button
            >
            <el-button
              type="primary"
              link
              v-if="row.certificationStatus != 0"
              @click="openDialog(row)"
              >入驻资料</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 开始办证弹窗 -->
    <el-dialog
      v-model="startDialogVisible"
      title="开始办证"
      width="400px"
      @close="resetStartDialog"
      class="certificate-dialog"
    >
      <el-form
        :model="startForm"
        label-width="90px"
        :rules="startRules"
        ref="startFormRef"
        class="dialog-form"
      >
        <el-form-item label="办证方式" prop="certificationType">
          <el-radio-group v-model="startForm.certificationType">
            <el-radio label="我方代办">我方代办</el-radio>
            <el-radio label="企业自办">企业自办</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="办证人" prop="certificationPersonnel">
          <el-input
            v-model="startForm.certificationPersonnel"
            placeholder="请输入办证人"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="startDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleStartSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 办证材料上传弹窗 -->
    <el-dialog
      v-model="certificationDialogVisible"
      title="上传办证材料"
      width="800px"
      @close="resetCertificationDialog"
    >
      <el-card class="material-block" style="margin-top: 18px" shadow="never">
        <div class="material-inner-row">
          <div class="upload-vertical">
            <div class="upload-section">
              <div class="upload-label">法人签字笔迹</div>
              <el-upload
                class="upload-demo"
                :show-file-list="true"
                :auto-upload="true"
                :file-list="fileListSign"
                :before-upload="(file) => beforeUpload(file, 2)"
                :on-change="(f, fl) => handleFileChange('sign', f, fl)"
                :on-preview="(file) => handleFilePreview(file, 'sign')"
                :on-remove="(file) => handleFileRemove('sign', file)"
                :multiple="true"
                accept="image/*"
              >
                <el-button type="primary">上传法人签字笔迹</el-button>
              </el-upload>
            </div>
            <div class="upload-section">
              <div class="upload-label">自然人身份证</div>
              <el-upload
                class="upload-demo"
                :show-file-list="true"
                :auto-upload="true"
                :file-list="fileListId"
                :before-upload="(file) => beforeUpload(file, 3)"
                :on-change="(f, fl) => handleFileChange('id', f, fl)"
                :on-preview="(file) => handleFilePreview(file, 'id')"
                :on-remove="(file) => handleFileRemove('id', file)"
                :multiple="true"
                accept="image/*"
              >
                <el-button type="primary">上传自然人身份证</el-button>
              </el-upload>
            </div>
            <div class="upload-section">
              <div class="upload-label">非自然人营业执照</div>
              <el-upload
                class="upload-demo"
                :show-file-list="true"
                :auto-upload="true"
                :file-list="fileListLicense"
                :before-upload="(file) => beforeUpload(file, 4)"
                :on-change="(f, fl) => handleFileChange('license', f, fl)"
                :on-preview="(file) => handleFilePreview(file, 'license')"
                :on-remove="(file) => handleFileRemove('license', file)"
                :multiple="true"
                accept="image/*"
              >
                <el-button type="primary">上传非自然人营业执照</el-button>
              </el-upload>
            </div>
            <div class="upload-section">
              <div class="upload-label">营业执照</div>
              <el-upload
                class="upload-demo"
                :show-file-list="true"
                :auto-upload="true"
                :file-list="fileListLicensePdf"
                :before-upload="(file) => beforeUpload(file, 12)"
                :on-change="(f, fl) => handleFileChange('licensePdf', f, fl)"
                :on-preview="(file) => handleFilePreview(file, 'licensePdf')"
                :on-remove="(file) => handleFileRemove('licensePdf', file)"
                accept="*"
                list-type="text"
              >
                <el-button type="primary">上传营业执照</el-button>
              </el-upload>
            </div>
          </div>

          <div class="block-img"></div>
        </div>
      </el-card>
      <template #footer>
        <el-button @click="certificationDialogVisible = false">关闭</el-button>
        <el-button
          type="primary"
          @click="handleCompleteCertification"
          :disabled="!fileListLicensePdf.length"
        >
          完成办证
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";

import { getCertificationList, updateCertification } from "@/api/certificate/index.js";
import {
  getFileByCompanyIdAndTag,
  companyUploadFile,
  deleteFile,
} from "@/api/company/index.js";
// 只保留日期部分
function dateOnlyFormatter(row, column, cellValue) {
  if (!cellValue) return "";
  return String(cellValue).split(" ")[0].split("T")[0];
}
const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();

const loading = ref(false);
const total = ref(0);
const certificateList = ref([]);
const activeTab = ref("0");
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  companyName: "",
  entryMode: "",
  zt: "",
  certificationStatus: 0, // 0:待办证, 1:办证中, 2:已办结
});

// 弹窗相关
const startDialogVisible = ref(false);
const startFormRef = ref();
const certificationDialogVisible = ref(false);
const fileListSign = ref([]);
const fileListId = ref([]);
const fileListLicense = ref([]);
const currentCertificationRow = ref(null);

const startForm = reactive({
  certificationType: "我方代办",
  certificationPersonnel: "",
  companyId: "",
  certificationStatus: 1,
  id: "",
  companyStatus: "",
  companyClass: "",
  entryMode: "",

  type: "Operation",
});
const startRules = {
  certificationType: [{ required: true, message: "请选择办证方式", trigger: "change" }],
  certificationPersonnel: [{ required: true, message: "请输入办证人", trigger: "blur" }],
};

function getList() {
  loading.value = true;
  getCertificationList(queryParams)
    .then((res) => {
      if (res && res.code === 200) {
        certificateList.value = Array.isArray(res.rows) ? res.rows : [];
        total.value = res.total || 0;
      } else {
        certificateList.value = [];
        total.value = 0;
      }
    })
    .catch(() => {
      certificateList.value = [];
      total.value = 0;
    })
    .finally(() => {
      setTimeout(() => {
        loading.value = false;
      }, 300);
    });
}

function handleTabChange(tab) {
  queryParams.certificationStatus = Number(tab.paneName);
  queryParams.pageNum = 1;
  getList();
}
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}
function resetQuery() {
  queryParams.companyName = "";
  queryParams.certificationType = "";
  queryParams.pageNum = 1;
  queryParams.entryMode = "";
  queryParams.zt = "";
  getList();
}
function openDialog(row) {
  // 跳转前参数校验，防止companyId等为undefined导致路由报错
  if (!row.companyId) {
    proxy.$modal.msgWarning("缺少companyId，无法跳转") ||
      alert("缺少companyId，无法跳转");
    return;
  }
  if (row.entryMode == "实体") {
    router.push({
      path: "/companyStep",
      query: {
        companyId: row.companyId,
        companyStatus: row.status || "",
        entryMode: row.entryMode || "",
        companyClass: row.companyClass || "",
        companyName: row.companyName || "",
        zt: row.zt || "",
        type: "Operation",
        carrieType: row.carrieType || "",
      },
    });
  } else if (row.entryMode == "挂靠") {
    router.push({
      path: "/companyStepVirtual",
      query: {
        companyId: row.companyId,
        companyStatus: row.status || "",
        entryMode: row.entryMode || "",
        companyClass: row.companyClass || "",
        companyName: row.companyName || "",
        zt: row.zt || "",
        type: "Operation",
        carrieType: row.carrieType || "",
      },
    });
  }
}

// 查看企业档案
const viewCompanyProfile = (companyId) => {
  router.push({
    path: "/lookCompany",
    query: { companyId },
  });
};
// 打开弹窗
function openStartDialog(row) {
  startForm.companyClass = row.companyClass;
  startForm.entryMode = row.entryMode;
  startForm.companyStatus = row.status;
  startForm.companyName = row.companyName;
  startForm.zt = row.zt;
  startForm.certificationType = "我方代办";
  startForm.certificationPersonnel = "";
  startForm.companyId = row.companyId;
  startForm.certificationStatus = 1;
  startForm.id = row.id;

  startForm.type = "Operation";
  startDialogVisible.value = true;
}

// 重置弹窗
function resetStartDialog() {
  startForm.certificationType = "我方代办";
  startForm.certificationPersonnel = "";
  startForm.companyId = "";
  startForm.certificationStatus = 1;
  startForm.id = "";
  startForm.type = "Operation";
}

// 提交办证
async function openCertificationDialog(row) {
  certificationDialogVisible.value = true;
  currentCertificationRow.value = row;

  // 初始化文件列表
  fileListSign.value = [];
  fileListId.value = [];
  fileListLicense.value = [];
  fileListLicensePdf.value = [];
  // 获取已有的文件
  if (row.companyId) {
    await refreshFileListByTag(2);
    await refreshFileListByTag(3);
    await refreshFileListByTag(4);
    await refreshFileListByTag(12);
  }
}

function resetCertificationDialog() {
  fileListSign.value = [];
  fileListId.value = [];
  fileListLicense.value = [];
  currentCertificationRow.value = null;
}

// 上传前处理，调用companyUploadFile接口
async function beforeUpload(file, tag) {
  try {
    const companyId = currentCertificationRow.value.companyId;

    // 调用上传接口
    const formData_company = new FormData();
    console.log(companyId, file, tag);
    formData_company.append("companyId", companyId);
    formData_company.append("file", file);
    formData_company.append("tag", tag);
    console.log(formData_company);
    const res = await companyUploadFile(formData_company);
    console.log(res);
    if (res.code === 200) {
      ElMessage.success("上传成功");
      // 刷新文件列表
      await refreshFileListByTag(tag);
    } else {
      ElMessage.error(res.msg || "上传失败");
    }
    return false; // 阻止el-upload默认上传
  } catch (e) {
    console.error("上传失败:", e);
    ElMessage.error("上传失败，请重试");
    return false;
  }
}

// 刷新单个tag的文件列表
async function refreshFileListByTag(tag) {
  const companyId = currentCertificationRow.value?.companyId;
  if (!companyId) return;

  const params = {
    pageNum: 1,
    pageSize: 20,
    companyId,
    tag,
  };

  try {
    const res = await getFileByCompanyIdAndTag(params);
    const files = ((res && res.rows) || []).map((f) => ({
      id: f.id,
      name: f.fileName || "",
      url: f.url,
    }));
    if (tag === 0) fileListRecord.value = files;
    else if (tag === 13) fileListRecordOk.value = files;
    else if (tag === 1) fileListInfo.value = files;
    else if (tag === 2) fileListSign.value = files;
    else if (tag === 3) fileListId.value = files;
    else if (tag === 4) fileListLicense.value = files;
    else if (tag === 7) fileListContractArchive.value = files;
    else if (tag === 14) fileListVirtualArchive.value = files;
    else if (tag === 15) fileListBeforeDecoration.value = files;
    else if (tag === 16) fileListAfterDecoration.value = files;
    else if (tag === 9) fileListPropertyHandover.value = files;
    else if (tag === 11) fileListPlanPdf.value = files;
    else if (tag === 19) fileListPlanZip.value = files;
    else if (tag === 17) fileListWaterMeter.value = files;
    else if (tag === 18) fileListElectricMeter.value = files;
    else if (tag === 12) fileListLicensePdf.value = files;
  } catch (e) {
    // 可选： proxy.$modal.msgError("文件刷新失败");
  }
}
const fileListBeforeDecoration = ref([]);
const fileListAfterDecoration = ref([]);
const fileListPropertyHandover = ref([]);
const fileListPlanPdf = ref([]);
const fileListPlanZip = ref([]);
const fileListWaterMeter = ref([]);
const fileListElectricMeter = ref([]);
const fileListLicensePdf = ref([]);
// 合同归档文件上传/预览/删除复用原有逻辑
function handleFileChange(type, file, fileListArr) {
  if (type === "record") fileListRecord.value = fileListArr;
  if (type === "record_ok") fileListRecordOk.value = fileListArr;

  if (type === "info") fileListInfo.value = fileListArr;
  if (type === "sign") fileListSign.value = fileListArr;
  if (type === "id") fileListId.value = fileListArr;
  if (type === "license") fileListLicense.value = fileListArr;
  if (type === "contractArchive") fileListContractArchive.value = fileListArr;
  if (type === "virtualArchive") fileListVirtualArchive.value = fileListArr;
  if (type === "beforeDecoration") fileListBeforeDecoration.value = fileListArr;
  if (type === "afterDecoration") fileListAfterDecoration.value = fileListArr;
  if (type === "propertyHandover") fileListPropertyHandover.value = fileListArr;
  if (type === "planPdf") fileListPlanPdf.value = fileListArr;
  if (type === "planZip") fileListPlanZip.value = fileListArr;
  if (type === "waterMeter") fileListWaterMeter.value = fileListArr;
  if (type === "electricMeter") fileListElectricMeter.value = fileListArr;
  if (type === "licensePdf") fileListLicensePdf.value = fileListArr;
}

async function handleFileRemove(type, file) {
  if (!file.id) {
    // 归档文件上传后el-upload会自动触发on-remove，临时文件无id，直接忽略不报错
    return;
  }
  try {
    await deleteFile({ id: file.id });
    // 删除后刷新对应tag的文件列表
    let tag = 0;
    if (type === "record") tag = 0;
    else if (type === "record_ok") tag = 13;
    else if (type === "info") tag = 1;
    else if (type === "sign") tag = 2;
    else if (type === "id") tag = 3;
    else if (type === "license") tag = 4;
    else if (type === "contractArchive") tag = 7;
    else if (type === "virtualArchive") tag = 14;
    await refreshFileListByTag(tag);
    proxy.$modal.msgSuccess("删除成功");
  } catch (e) {
    console.error("删除失败:", e);
  }
}
function handleFilePreview(file) {
  if (file.url) {
    window.open(file.url, "_blank");
  }
}
async function handleCompleteCertification() {
  if (!currentCertificationRow.value) return;

  try {
    const params = {
      id: currentCertificationRow.value.id,
      companyId: currentCertificationRow.value.companyId,
      certificationStatus: 2, // 办结状态
    };

    const res = await updateCertification(params);
    if (res.code === 200) {
      ElMessage.success("办证完成");
      certificationDialogVisible.value = false;
      getList(); // 刷新列表
    } else {
      ElMessage.error(res.msg || "操作失败");
    }
  } catch (e) {
    ElMessage.error("操作失败");
  }
}

function handleStartSubmit() {
  startFormRef.value.validate(async (valid) => {
    if (!valid) return;
    const params = {
      id: startForm.id,
      companyId: startForm.companyId,
      certificationType: startForm.certificationType,
      certificationPersonnel: startForm.certificationPersonnel,
      certificationStatus: 1,
    };
    try {
      const res = await updateCertification(params);
      if (res.code === 200) {
        ElMessage.success("已开始办证");
        startDialogVisible.value = false;
        // 跳转到companyStep的备案环节
        router.push({
          path: "/companyStep",
          query: {
            companyId: startForm.companyId,
            companyStatus: startForm.companyStatus || "",
            companyClass: startForm.companyClass || "",
            companyName: startForm.companyName || "",
            zt: startForm.zt || "",
            entryMode: startForm.entryMode || "",
            type: "Operation",
            carrieType: startForm.carrieType || "",
          },
          params: {
            companyId: startForm.companyId,
            companyStatus: startForm.companyStatus || "",
            companyClass: startForm.companyClass || "",
            companyName: startForm.companyName || "",
            zt: startForm.zt || "",
            entryMode: startForm.entryMode || "",
            carrieType: startForm.carrieType || "",
          },
        });
      } else {
        ElMessage.error(res.msg || "操作失败");
      }
    } catch (e) {
      ElMessage.error("操作失败");
    }
  });
}

onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
.record-container {
  padding: 24px 32px 0 32px;
  /* background: #fff; */
  min-height: 100vh;
}

.certificate-table-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
  border-radius: 14px;
  padding: 24px 0 0 0 !important;
}

.certificate-table {
  font-size: 15px;
  border-radius: 14px;
  /* background: #fff; */
  --el-table-row-hover-bg-color: #f6faff;
  --el-table-border-color: #e4e7ed;
  --el-table-header-bg-color: #f8fafb;
  --el-table-header-text-color: #333;
  --el-table-row-bg-color: #fff;

  th,
  td {
    padding: 14px 0 !important;
    height: 54px !important;
  }
}

.certificate-dialog {
  border-radius: 10px;
}

.material-upload-row {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}

.upload-section {
  flex: 1;
  min-width: 250px;
  margin-bottom: 20px;
}

.upload-label {
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
  font-size: 14px;
}

.upload-demo {
  margin-top: 8px;
}
</style>
